#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKeyboard.h>
#import <LockInfo/Plugin.h>

#import "framework/FWDetailListView.h"
#import "framework/FWApplication.h"
#import "framework/FWPlugin.h"
#import "framework/FWCommon.h"
#import "framework/FWPreferences.h"
#import "framework/FWPopupView.h"
#import "framework/FWDBAccess.h"

#import "PITaskSearch.h"
#import "PITask.h"
#import "PITaskIntegration.h"
#import "PITaskNative.h"
#import "PICommon.h"
#import "PITaskPreview.h"


@implementation PITaskSearch

@synthesize preferences, popupView;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)rect application:(FWApplication*)appl preferences:(FWPreferences*)prefs
{
    if ((self = [super initWithFrame:rect caption:@"Search Task/Title" label:@"Search Task/Name" prompt:@"Search Task/Name Prompt" application:appl preferences:prefs])) {
        self.preferences = prefs;
        
        CGRect constraint = rect;
        constraint.origin.x = 0;
        constraint.origin.y = 0;
        constraint.size.height = 200;
        
        // Define a hidden view that will be used to position any popup errors in
        // order to avoid the keyboard
        self.popupView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
        UIView* constrain = [[[UIView alloc] initWithFrame:constraint] autorelease];
        constrain.backgroundColor = [UIColor clearColor];
        constrain.userInteractionEnabled = NO;
        constrain.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [constrain addSubview:popupView];

        [self addSubview:constrain];
        
        self.text.autocapitalizationType = UITextAutocapitalizationTypeNone;
    }
    
    return self;
}

- (void)dealloc
{
    [preferences release];
    [popupView release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Command button callbacks

- (void)doneClicked
{
    NSString* todoTitle = self.text.text;
    
    XLog(@"LI:PITask: New todo to be created: %@", todoTitle);
    
    if (self.hasFired)
        return;
    else
        self.hasFired = YES;
    
    [self.application.fwPlugin hideToolbar];
    
    FWDatabase* database = nil;
    NSMutableArray* tasks = nil;
    @try {
        database = FWDBConnectDatabase(self.application.databasePath, self.application);
        tasks = [PITaskIntegration basicTaskList:self.application
                                        database:database
                                           prefs:self.preferences
                                             key:nil
                                       parentKey:nil
                                          search:self.text.text];
        
        [tasks addObjectsFromArray:[PITaskNative basicTaskList:self.application
                                                      database:nil
                                                         prefs:self.preferences
                                                           key:nil
                                                        search:self.text.text]];
        
        [tasks sortUsingFunction:compareNativeTaskTitles context:nil];
    }
    @finally {
        FWDBDisconnectDatabase(database);
    }
    

    // No items found?
    if (!tasks || (tasks.count == 0)) {
        self.hasFired = NO;
        CGRect frame = popupView.frame;
        frame.size.height = self.text.frame.origin.y + self.text.frame.size.height * 2;
        [FWPopupView displayPopupMessage:localize([NSBundle bundleForClass:[self class]], @"Search Task/No Match")
                                   color:self.isLightBackground ? nil : [UIColor darkGrayColor]
                                 forView:popupView];
        return;
    }
    

    // Hide the keyboard and remove all the input elements from the
    // view
    [self hideKeyboard:NO];
    NSArray* subviewList = [self.subviews retain];
    for (UIView* subview in subviewList)
        [subview removeFromSuperview];
    [subviewList release];

    // Create a view to show the preview list
    CGRect viewRect = self.frame;
    viewRect.origin.x = viewRect.origin.y = 0;
    PITaskPreview* previewData = [[[PITaskPreview alloc] initWithApplication:self.application] autorelease];
    FWDetailListView *thePreview = [[[FWDetailListView alloc] initWithFrame:viewRect
                                                                       list:tasks
                                                                      index:0
                                                                    caption:@"ListView/Item %i/%i"
                                                                application:self.application
                                                                   delegate:previewData] autorelease];
    previewData.controlDelegate = thePreview;
    
    // Add the preview to our display
    [self addSubview:thePreview];

    // Display with a nice transition
    CATransition *animation = [CATransition animation];
    [animation setType:@"cube"];
    [animation setSubtype:kCATransitionFromBottom];
    [animation setDuration:0.3];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFillMode: @"extended"];
    
    [[self layer] addAnimation:animation forKey:@"reloadAnimation"];
}

@end
